#页面基类

#封装：
    # 一些通用的属性：driver、base_url
    #一些通用的UI操作:点击某元素、输入某元素、打开某网址等等
import time
import autoit
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains

class PageBase(object):
    def __init__(self,driver,base_url):
        self.driver=driver
        self.base_url=base_url


    #打开某url
    def open(self,url):#"/simple/login"
        self.driver.get(self.base_url+url)

    #定位元素
    def find_element(self,loc):
        by=loc[0]
        value=loc[1]
        return self.driver.find_element(by,value)

    def find_elements(self,loc):
        by=loc[0]
        value=loc[1]
        return self.driver.find_elements(by,value)


    #点击某元素
    def click(self,loc):
        self.find_element(loc).click()

    #给某元素输入数据
    ##适合控件：文本框、密码框、多行文本框
    def input(self,loc,data):
        self.find_element(loc).send_keys(data)

    # 对文本框/密码框/多行文本框进行清空并输入数据：不会触发鼠标失去焦点事件
    def clearAndInput(self, loc, data):
        ele = self.find_element(loc)
        ele.send_keys(Keys.CONTROL, 'a')#ctrl+A
        ele.send_keys(Keys.BACK_SPACE)
        ele.send_keys(data)

    # 清空文本框/密码框/多行文本框（会让鼠标失去焦点，触发前端的失去焦点）
    def clear(self, loc):
        self.find_element(loc).clear()

    #获取某元素的文本内容(掐头去尾)
    def getEleText(self,loc):
        return self.find_element(loc).text.strip()

    #获取某元素的某属性的值（切头去尾）
    def getEleAttr(self,loc,attrName):
        return self.find_element(loc).get_attribute(attrName).strip()

    # 单选按钮控件：选中某选项
    def selectRaidoOption(self, attr_name, selectOptionValue):
        self.driver.find_element_by_css_selector(
            f"input[type='radio'][name='{attr_name}'][value='{selectOptionValue}']").click()

    # 复选框控件：选中0个/1个或N个选项。
    def selectCheckBoxOptions(self, attr_name, selectOptionsValues):
        allOption = self.driver.find_elements_by_css_selector(f"input[type='checkbox'][name='{attr_name}']")
        for one in allOption:
            attr_value = one.get_attribute("value")
            selectStatus = one.is_selected()  # 获取该选项的原始选中状态
            if attr_value in selectOptionsValues:  # 该选项确保选中
                if selectStatus:
                    pass
                else:
                    one.click()
            else:  # 该选项确保不选中
                if selectStatus:
                    one.click()
                else:
                    pass

    # 下拉列表控件：选中某选项
    def selectSelectOption(self, attr_name, selectOptionText):
        select = Select(self.driver.find_element_by_css_selector(f"select[name='{attr_name}']"))
        select.select_by_visible_text(selectOptionText)  # 推荐

    # 适合：日期控件
    # 输入某日期
    def date_input(self, loc, value):
        ele = self.find_element(loc)
        self.driver.execute_script(f"arguments[0].value='{value}'", ele)

    # 文件框：上传1个或N个文件/文件夹：实现方法1
    def uploadFiles1(self, loc_file, filePaths):
        if filePaths=="" or filePaths == None:
            return
        if "," in filePaths:  # 如果是上传多个
            filePaths = filePaths.replace(",", "\n")
            self.find_element(loc_file).send_keys(filePaths)
        else:  # 如果是上传1个
            self.find_element(loc_file).send_keys(filePaths)

    def uploadFiles2(self,loc_file,filePaths):
        if filePaths=="" or filePaths == None:
            return

        ele = self.find_element(loc_file)
        ActionChains(self.driver).click(ele).perform()
        time.sleep(2)

        a = filePaths.split(",")
        newFilePath = ""
        for x in a:
            newFilePath += '"' + x + '" '
        newFilePath = newFilePath.replace("/", "\\")
        autoit.win_wait("打开", 10)
        autoit.control_send("打开", "Edit1", newFilePath)
        autoit.control_click("打开", "Button1")

    # 处理JS三种弹出框
    # 获取三种JS弹出框的文本内容
    def getTextForJsTanCuKuan(self):
        return self.driver.switch_to.alert.text

    # 点击三种JS弹出框的“确定”按钮
    def acceptForJsTanCuKuan(self):
        self.driver.switch_to.alert.accept()

    # 点击三种JS弹出框的“取消”按钮
    def dismissForJsTanCuKuan(self):
        self.driver.switch_to.alert.dismiss()

    # 为JS的prompt弹出框输入文本
    def inputJsTanCuKuan(self, data):
        self.driver.switch_to.alert.send_keys(data)

    # iframe框架相关处理
    # 切换到某iframe
    def switch_iframe(self, loc_iframe):
        ele_ifame = self.find_element(loc_iframe)
        self.driver.switch_to.frame(ele_ifame)

    # 切换到主iframe
    def switch_defaultIframe(self):
        self.driver.switch_to.default_content()

    # 鼠标操作的相关处理
    # 函数功能：鼠标单击某元素loc
    def mouse_click(self, loc):
        ele = self.find_element(loc)
        ActionChains(self.driver).click(ele).perform()

    # 函数功能：鼠标双击某元素loc
    def mouse_dbclick(self, loc):
        ele = self.find_element(loc)
        ActionChains(self.driver).double_click(ele).perform()

    # 函数功能：鼠标悬停在某元素loc
    def mouse_moveToEle(self, loc):
        ele = self.find_element(loc)
        ActionChains(self.driver).move_to_element(ele).perform()

    # 函数功能：滑动垂直滚动条到最底部
    def scrollToFloor(self):
        js1 = "window.scrollTo(0,10000)"
        self.driver.execute_script(js1)

    # 网页截图
    def savePng1(self, filePath):
        self.driver.get_screenshot_as_file(filePath)

    def savePng2(self, fileName):
        self.driver.get_screenshot_as_file("./screen/" + fileName + ".png")

    def savePng3(self, serviceName, key):
        fileName = serviceName + "_" + key + "_" + time.strftime("%Y%m%d%H%M%S")
        self.driver.get_screenshot_as_file("./screen/" + fileName + ".png")
        return fileName#"登录_K001_20250507095012"

    # 切换标签页/切换窗口
    # 形参n是第几个窗口。n从0开始.-1：最新打开窗口
    def switch_windowByIndex(self, n):
        self.driver.switch_to.window(self.driver.window_handles[n])

    # 根据窗口标题（可以给部分）来切到对应的窗口换
    def switch_windowByTitle(self, target_title):
        moren_handler = self.driver.current_window_handle
        flag = True
        allWindows = self.driver.window_handles
        for one in allWindows:
            self.driver.switch_to.window(one)
            currentTitle = self.driver.title
            if target_title in currentTitle:
                flag = False
                break
            time.sleep(1)
        if flag:
            self.driver.switch_to.window(moren_handler)

    # 根据窗口url（可以给部分）来切到对应的窗口换
    def switch_windowByUrl(self, target_url):
        moren_handler = self.driver.current_window_handle
        flag = True
        allWindows = self.driver.window_handles
        for one in allWindows:
            self.driver.switch_to.window(one)
            currentUrl = self.driver.current_url
            if target_url in currentUrl:
                flag = False
                break
            time.sleep(1)
        if flag:
            self.driver.switch_to.window(moren_handler)